package com.nyp.remoter.ejb;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.PersistenceContext;

import com.nyp.remoter.entity.User;

@Stateless
public class EntityIsolationEJB {
	
	@PersistenceContext
	EntityManager em;
	
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public User findUserByIDAndWait(Long userId, int secondsToDelay){
		User user = em.find(User.class, userId, LockModeType.OPTIMISTIC);
		try {
			Thread.sleep(secondsToDelay*1000);
		} 
		catch (InterruptedException e) {
			e.printStackTrace();
		}
		//user.setName("nameSetByfindUserByIDAndWait");
		return user;
	}
	
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void changeUserName(Long userId, String newName){
		User user = em.find(User.class, userId);
		user.setName(newName);
	}
}
